package com.example.myapplication.audio;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;

import com.example.myapplication.bean.AudioBean;
import com.example.myapplication.utils.Contains;

import java.io.IOException;
import java.util.List;

public class AudioService extends Service implements MediaPlayer.OnCompletionListener {
    private MediaPlayer mediaPlayer = null;
    private List<AudioBean> mList;//播放列表
    int playPosition = -1;//当前播放的是哪一个音频

    public AudioService() {
    }

    //接口回调开始
    public interface OnPlayChangedListener {
        public void playChange(int position);
    }

    private OnPlayChangedListener onPlayChangedListener;

    public void setOnPlayChangedListener(OnPlayChangedListener onPlayChangedListener) {
        this.onPlayChangedListener = onPlayChangedListener;
    }
    //结束

    @Override
    public void onCompletion(MediaPlayer mp) {
        mList.get(playPosition).setPlaying(false);
        mList.get(playPosition).setPaused(false);
    }


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new AudioBinder();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeMusic();
    }

    public class AudioBinder extends Binder {
        public AudioService getService() {
            return AudioService.this;
        }
    }

    public void notifyActivityRefreshUI() {
        if (onPlayChangedListener != null) {
            onPlayChangedListener.playChange(playPosition);
        }
    }



    /**
     * 播放状态
     */
    public void cutMusicOrPause(int position) throws IOException {
        int i = this.playPosition;
        if (position != i) {
            //判断是否正在播放，如果
            if (i != -1) {

                mList.get(i).setPlaying(false);
                mList.get(i).setPaused(false);
            }
            play(position);
            return;
        }
        pauseOrContinueMusic();
    }

    /**
     * 音频播放
     */
    public void play(int position) throws IOException {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            //设置监听事件
            mediaPlayer.setOnCompletionListener(this);
        }
        //播放时获取当前歌曲列表，判断是否有歌曲
        mList = Contains.getMyAudioList();
        if (mList.size() <= 0) {
            return;
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        playPosition = position;
        //设置音频资源路径
        mediaPlayer.setDataSource(mList.get(position).getPath());
        mediaPlayer.prepare();
        mediaPlayer.start();
        mList.get(position).setPlaying(true);
        notifyActivityRefreshUI();
        setFlagCtlThread(true);
        updateProgress();
    }

    /**
     * 暂停，继续播放
     */
    public void pauseOrContinueMusic() {
        int playPosition = this.playPosition;
        AudioBean audioBean = mList.get(playPosition);
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            audioBean.setPlaying(false);
            audioBean.setPaused(true);
        } else {
            mediaPlayer.start();
            audioBean.setPlaying(true);
            audioBean.setPaused(false);

        }
        notifyActivityRefreshUI();

    }


    /**
     * 关闭音乐
     */
    public void closeMusic() {
        if (mediaPlayer != null) {
            setFlagCtlThread(false);
            mediaPlayer.stop();
            playPosition = -1;
        }
    }



    //更新播放进度
    private boolean flag = true;
    private final int PROGRESS_ID = 1;
    private final int INTERMEDIATE_TIME = 1000;

    public void setFlagCtlThread(boolean flag) {
        this.flag = flag;
    }

    public void updateProgress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    long total = mList.get(playPosition).getDurationLong();
                    int currentPosition = mediaPlayer.getCurrentPosition();//当前播放的位置
                    //计算播放进度
                    int progress = (int) (currentPosition * 100 / total);
                    mList.get(playPosition).setProgress(progress);
                    handler.sendEmptyMessageDelayed(PROGRESS_ID, INTERMEDIATE_TIME);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == PROGRESS_ID) {
                notifyActivityRefreshUI();
            }
            return true;
        }
    });




}

